<?php
namespace app\component\controller;

use app\common\base\BasicRest;
use think\Config;
use think\Db;
use think\Request;
use app\component\controller\Wechatsdk;
use think\Cache;


class Wechatjs extends  BasicRest
{

    public function __construct()
    {
        parent::__construct();
    }

    protected function validatecsrf(){
        // $csrf=$this->request->post('_CSRF');
        // if($csrf&&strlen($csrf)==12){
        //     $onedata=substr($csrf,0,4);
        //     $twodata=substr($csrf,4,4);
        //     $threedata=substr($csrf,8,4);
        //     $result= substr((string)((int)$onedata*(int)$threedata),0,4);
        //     if($result!=$twodata){
        //         echo '非法请求';
        //         exit(0);
        //     }
        // }else{
        //     echo '非法请求';
        //         exit(0);
        // }
         
    }
        
    public function getjstoken(){
            $appid=Config::get('wechatid');
            $appsecret=Config::get('wechatAppSecret');
                //获取accesstoken
            if(!$token=Cache::get('accesstoken')){

                    $curl = curl_init();
                    curl_setopt($curl, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret");
                    // curl_setopt($curl, CURLOPT_HEADER, 1);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                    $data = curl_exec($curl);
                    curl_close($curl);
                    $data=json_decode($data,true);
                    $token=$data['access_token'];
                    Cache::set('accesstoken',$token,7000);
            }
            return $token;
    }
   
   //公众号统一下单
   public function gongzhongtongyixiadan($data,$openid){
        $wechatsdk=new Wechatsdk(Config::get('wechatid'),Config::get('mch_id'),Config::get('wechatnotify_url'),Config::get('wechatkey'));
        
        //参数
        $params=[];
        $params['appid']=Config::get('wechatid');
        $params['mch_id']=Config::get('mch_id');
        $params['nonce_str']=$wechatsdk->genRandomString();
        $params['body']="爱粉象优惠商品购买";
        $params['attach']=$data['active_time'];
        $params['out_trade_no']=$data['order_id'];
        $params['total_fee']=$data['totalprice']*100;
        $params['spbill_create_ip']=$_SERVER['REMOTE_ADDR'];
        $params['notify_url']=Config::get('wechatnotify_url');
        $params['trade_type']="JSAPI";
        $params['openid']=$openid;
        $params['sign']=$wechatsdk->MakeSign($params);
        $xml = $wechatsdk->data_to_xml($params);
        $response=$wechatsdk->postXmlCurl($xml,"https://api.mch.weixin.qq.com/pay/unifiedorder");
        $result = $wechatsdk->xml_to_data( $response );
        
        return $result;
   }

   //小程序获取asscentoken

   static public function xiaochengxuma($postdata,$num){
  
        //先判断access_token有没有过期
            $access_token=Cache::get('xiaochengxumaaccess_token');
            if(!$access_token){
                    $wechatAppSecret=Config::get('wechatAppSecret');
                    $appid=Config::get('wechatAppappid');
                    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$wechatAppSecret;
                    
                    $ch = curl_init(); 
                    curl_setopt($ch, CURLOPT_URL, $url); 
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                      //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
                    $output = json_decode(curl_exec($ch),true); 
                    curl_close($ch); 
                  
                $access_token=$output['access_token'];
                Cache::set('xiaochengxumaaccess_token',$output['access_token'],7000);
            }
                    
                    if($num==1){
                        $path='活动小程序码'.time().$num.'.png';
                    }elseif($num==2){
                        $path='管理员小程序码'.time().$num.'.png';
                    }
                    
                    $dir = dirname(__FILE__)."/../../../public/xiaochengxu/".date("Y-m-d");
                    if (is_dir($dir) || @mkdir($dir, 0777)){

                    }else{
                        return res_fail('二维码创建失败');
                        exit;
                    };

                    $codeurl="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
                    $curl = curl_init(); 
                    curl_setopt($curl, CURLOPT_URL, $codeurl); 
                    // curl_setopt($curl, CURLOPT_HEADER, 0);
                      //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
                    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); 
                    curl_setopt($curl, CURLOPT_POST, 1);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postdata));
                    $output = curl_exec($curl); 
                   
                    file_put_contents($dir.'/'.$path,$output);
                    curl_close($curl); 
                
                    return $dir.'/'.$path;
   }


   //小程序统一下单
   public function xiaochengxutongyixiadan($data,$openid){
        $appid=Config::get('wechatAppappid');
        $mch_id=Config::get('mch_id');
        $notify_url=Config::get('wechatnotify_url');
        $wechatsdk=new Wechatsdk($appid,$mch_id,$notify_url,Config::get('wechatkey'));
        
        //参数
        $params=[];
        
        $params['appid']=$appid;
        $params['mch_id']=$mch_id;
        $params['nonce_str']=$wechatsdk->genRandomString();
        $params['body']="爱粉象预购商品购买";
        $params['attach']=$data['active_time'];
        $params['out_trade_no']=$data['order_id'];
        $params['total_fee']=$data['totalprice']*100;
        $params['spbill_create_ip']=$_SERVER['REMOTE_ADDR'];
        $params['notify_url']=$notify_url;
        $params['trade_type']="JSAPI";
        $params['openid']=$openid;
        $params['sign']=$wechatsdk->MakeSign($params);
        $xml = $wechatsdk->data_to_xml($params);
        $response=$wechatsdk->postXmlCurl($xml,"https://api.mch.weixin.qq.com/pay/unifiedorder");
        $result = $wechatsdk->xml_to_data( $response );
     
        if($result['return_code']=='FAIL'){
            return false;
        }
       
        $par=[];
        $par["appId"]=$appid;
        $par['timeStamp']=(string)time();
        $par['nonceStr']=$wechatsdk->genRandomString();
        $par['package']="prepay_id=".$result['prepay_id'];
        $par['signType']='MD5';
        $par['paySign']=$wechatsdk->MakeSign($par);
        //生成小程序的支付参数    
        return $par;
        // return $result;
   }

    static public function xiaochengxumaanzhuo($postdata,$num){
  
        //先判断access_token有没有过期
            $access_token=Cache::get('xiaochengxumaaccess_token');
            if(!$access_token){
                    $wechatAppSecret=Config::get('wechatAppSecret');
                    $appid=Config::get('wechatAppappid');
                    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$wechatAppSecret;
                    
                    $ch = curl_init(); 
                    curl_setopt($ch, CURLOPT_URL, $url); 
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                      //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
                    $output = json_decode(curl_exec($ch),true); 
                    curl_close($ch); 
                  
                $access_token=$output['access_token'];
                Cache::set('xiaochengxumaaccess_token',$output['access_token'],7000);
            }
                    
                    // if($num==1){
                        $path=$postdata['filename'];
                    // }elseif($num==2){
                    //     $path='管理员小程序码'.time().$num.'.png';
                    // }
                    $date=date("Y-m-d");
                    $dir = dirname(__FILE__)."/../../../public/anzhuoji/".$date;
                    if (is_dir($dir) || @mkdir($dir, 0777)){

                    }else{
                        return res_fail('二维码创建失败');
                        exit;
                    };

                    $codeurl="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
                    $curl = curl_init(); 
                    curl_setopt($curl, CURLOPT_URL, $codeurl); 
                    // curl_setopt($curl, CURLOPT_HEADER, 0);
                      //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
                    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); 
                    curl_setopt($curl, CURLOPT_POST, 1);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postdata));
                    $output = curl_exec($curl); 
                   
                    file_put_contents($dir.'/'.$path,$output);
                    curl_close($curl); 
                
                    return '/anzhuoji/'.$date.'/'.$path;
   }
   
}